import 'package:flutter/material.dart';
import './smscontroller.dart';

class AddTaskScreen extends StatefulWidget {
  @override
  _AddTaskScreenState createState() => _AddTaskScreenState();
}

class _AddTaskScreenState extends State<AddTaskScreen> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  bool _isButtonDisabled = true;
  bool _isCodeSent = false;
  int _countdown = 60;
  bool _mounted = true; // 添加一个变量来跟踪组件是否已挂载

  final SmsController _smsController = SmsController();

  void _updateState() {
    setState(() {
      _isCodeSent = true;
      _startCountdown();
    });
  }

  void _startCountdown() {
    Future.delayed(Duration(seconds: 1), () {
      if (_mounted && _countdown > 0) {
        setState(() {
          _countdown--;
        });
        _startCountdown();
      } else if (_mounted) {
        setState(() {
          _isCodeSent = false;
          _countdown = 60;
        });
      }
    });
  }

  @override
  void dispose() {
    _mounted = false; // 在dispose中设置为false
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final inputHeight = 60.0;
    final buttonHeight = inputHeight * 0.55;
    final buttonWidth = MediaQuery.of(context).size.width * 0.35;

    return GestureDetector(
      // 用于捕获点击事件，比如点击背景可以收起键盘
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
          ),
          child: Container(
            color: Color(0xff757575),
            child: Container(
              padding: EdgeInsets.all(20.0),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20.0),
                  topRight: Radius.circular(20.0),
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Text(
                    '识海 登录开启奇旅之行',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: MediaQuery.of(context).size.width * 0.06,
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 10),
                  Text(
                    '未注册手机号登录后自动注册账号',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: MediaQuery.of(context).size.width * 0.04,
                      color: Colors.grey,
                    ),
                  ),
                  SizedBox(height: 20),
                  TextField(
                    controller: _phoneController,
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.symmetric(vertical: inputHeight / 4), // 调整垂直填充以设置高度
                      prefixIcon: Icon(Icons.phone),
                      hintText: '输入您的手机号',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(30.0),
                      ),
                    ),
                    keyboardType: TextInputType.phone,
                    style: TextStyle(fontSize: 18.0),
                  ),
                  SizedBox(height: 10),
                  Stack(
                    children: <Widget>[
                      TextField(
                        controller: _codeController,
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.symmetric(vertical: inputHeight / 4), // 调整垂直填充以设置高度
                          prefixIcon: Icon(Icons.lock),
                          hintText: '输入验证码',
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(30.0),
                          ),
                        ),
                        onChanged: (value) {
                          setState(() {
                            _isButtonDisabled = value.isEmpty;
                          });
                        },
                        style: TextStyle(fontSize: 18.0),
                      ),
                      Positioned(
                        right: 10, // 向左移动5个单位
                        top: 6, // 向下移动10个单位
                        child: Container(
                          height: buttonHeight, // 设置为原本高度的0.4倍
                          width: buttonWidth, // 设置为屏幕宽度的0.5倍
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              elevation: 0,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(30.0),
                              ),
                            ),
                            child: _isCodeSent
                                ? Text('重发($_countdown)')
                                : Text('获取验证码'),
                            onPressed: _isCodeSent
                                ? null
                                : () async {
                                    await _smsController.sendCode(
                                      _phoneController.text,
                                      context,
                                      _updateState,
                                    );
                                  },
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 20),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.purple,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30.0),
                      ),
                      padding: EdgeInsets.symmetric(vertical: 14.0),
                    ),
                    child: Text('登录', style: TextStyle(fontSize: 18.0)),
                    onPressed: _isButtonDisabled
                        ? null
                        : () async {
                            await _smsController.verifyCodeAndLogin(
                              _phoneController.text,
                              _codeController.text,
                              context,
                            );
                            if (_mounted) { // 在调用 setState 之前检查 _mounted
                              setState(() {}); // 更新状态
                            }
                          },
                  ),
                  SizedBox(height: 20),
                  Text(
                    '✅ 已阅读并同意捏Ta《隐私政策》和《用户协议》及《互联网信息服务深度合成管理规定》',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: MediaQuery.of(context).size.width * 0.03,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
